<?php
if (! class_exists ( 'Smarty' )) {
	include_once NUTZP . 'libs/vendors/smarty/Smarty.class.php';
}
class SmartyView extends View {
	const EXT = '.tpl';
	/**
	 * @param array $data
	 * @param Response $response
	 * @param string $tpl
	 */
	public function render($data, $response, $tpl = '') {
		global $LAYOUT_NAME, $APPLICATION, $ACTION_NAME;
		$tpl .= SmartyView::EXT;
		$_tpl = $response->viewFile . SmartyView::EXT;
		if (is_file ( $tpl )) {
			$__smarty = new Smarty ();
			$__smarty->plugins_dir [] = NUTZP . 'libs/vendors/smarty/nutzp/';
			$__smarty->template_dir = $response->viewPath; //模板目录
			$__smarty->compile_dir = TMP . 'apptpls_c' . DS . $response->app; //模板编译目录
			$__smarty->cache_dir = TMP . 'apptpls_cache' . DS . $response->app; //模板缓存目录
			$__smarty = apply_filter ( 'init_smarty_view_engine', $__smarty );
			foreach ( $data as $n => $v ) {
				$__smarty->assign ( $n, $v ); //变量
			}
			return $__smarty->fetch ( $_tpl );
		} else {
			$response->error ( 'the view template ' . $tpl . ' is not found', 404 );
		}
	}
	
	public function setHeader() {
		@header ( 'Content-Type: text/html' );
	}
}
/**
 * Smarty app modifier plugin
 * 
 * Type:     modifier<br>
 * Name:     app<br>
 * Purpose:  输出模板所在目录下资源的URL
 * 
 * @param array $params 参数
 * @param unknown_type $compiler
 * @return string with compiled code
 */
function smarty_modifiercompiler_app($params, $compiler) {
	global $__cmd, $APPLICATION;
	static $base = null;
	if ($base == null) {
		$base = site_url ();
	}
	if (count ( $params ) > 1) {
		$app = $params [1];
	} else {
		$app = "'" . strtolower ( $APPLICATION ) . "'";
	}
	$jcs = $app . ".'/'." . $params [0];
	return "'{$base}'.jcs({$jcs})";
}
/**
 * 调用方法
 * 
 * @param unknown_type $params
 * @param unknown_type $compiler
 */
function smarty_modifiercompiler_func($params, $compiler) {
	$func = array_shift ( $params );
	return 'call_user_func_array(' . $func . ',' . var_export ( $params, true ) . ')';
}